package arithmetic;

/**
 * 滑动窗口
 * 209. 长度最小的子数组
 * https://leetcode-cn.com/problems/minimum-size-subarray-sum/solution/hua-dong-chuang-kou-209-chang-du-zui-xia-ljne/
 */
public class SlideWindow {

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 2, 4, 3};
//        int[] nums = {1, 1, 1, 1, 1,1};
        int target = 7;
        SlideWindow slideWindow = new SlideWindow();
        int i = slideWindow.minSubArrayLen(target, nums);
        System.out.println(i);

    }

    public int minSubArrayLen(int target, int[] nums) {
        //使用滑动窗口，result最长长度为，nums.length
        int low = 0, high = -1, sum = 0;
        int result = nums.length + 1;
        while (low < nums.length - 1) {
            //窗口右边伸开
            if (high < nums.length - 1 && sum < target) {
                high++;
                sum += nums[high];
            } else {
                //窗口左边收缩
                sum -= nums[low];
                low++;
            }
            //计算连续数组值，并记录最小的值
            if (sum >= target) {
                result = Math.min(high - low+1, result);
            }
        }
        //当result大于
        return result == nums.length + 1 ? 0 : result;
    }
}